package com.gp.billsrecord.ui.login

import android.content.Intent
import androidx.lifecycle.Observer
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import com.afollestad.materialdialogs.MaterialDialog
import com.gp.billsrecord.MainActivity
import com.gp.billsrecord.R
import com.gp.billsrecord.base.Const
import com.gp.billsrecord.databinding.ActivityLoginBinding
import com.xujichang.base.extensions.click
import com.xujichang.base.extensions.hideKeyBoard

/*登录页面*/
class LoginActivity : AppCompatActivity() {

    private val loginViewModel by viewModels<LoginViewModel>()
    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //关联页面
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //取页面的控件
        val username = binding.username
        val password = binding.password
        val login = binding.login
        val loading = binding.loading

        //监听输入内容是否合法
        loginViewModel.loginFormState.observe(this@LoginActivity, Observer {
            //为空直接返回
            val loginState = it ?: return@Observer

            //数据输入符合条件的时候，登录按钮可以使用
            login.isEnabled = loginState.isDataValid

            if (loginState.usernameError != null) {
                //提示错误
                username.error = getString(loginState.usernameError)
            }
            if (loginState.passwordError != null) {
                //提示错误
                password.error = getString(loginState.passwordError)
            }
        })
        //监听是否登录成功
        loginViewModel.loginResult.observe(this@LoginActivity, Observer {
            val loginResult = it ?: return@Observer
            //关闭loading
            loading.visibility = View.GONE

            if (loginResult.error != null) {
                showLoginFailed(loginResult.error)
                return@Observer
            }
            if (loginResult.success != null) {
                updateUiWithUser(loginResult.success)
            }
        })

        username.afterTextChanged {
            //每输入一个字符都会进行调用
            loginViewModel.loginDataChanged(
                username.text.toString(),
                password.text.toString()
            )
        }

        password.apply {
            afterTextChanged {
                //每输入一个字符都会进行调用
                loginViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

            //点击键盘上的完成按钮，会进行登录
            setOnEditorActionListener { text, actionId, _ ->
                when (actionId) {
                    EditorInfo.IME_ACTION_DONE -> {
                        //隐藏软键盘
                        text.hideKeyBoard()
                        loading.visibility = View.VISIBLE
                        loginViewModel.login(
                            username.text.toString(),
                            password.text.toString()
                        )
                    }
                }
                false
            }
            //登录按钮点击的时候进行登录
            login.click {
                it.hideKeyBoard()
                loading.visibility = View.VISIBLE
                loginViewModel.login(username.text.toString(), password.text.toString())
            }
        }
    }

    /**
     * 登录成功
     */
    private fun updateUiWithUser(loggedInUserView: LoggedInUserView) {
        Toast.makeText(
            applicationContext,
            "${loggedInUserView.displayName}登录成功",
            Toast.LENGTH_SHORT
        )
            .show()
        toMain()
    }

    /**
     * 跳转到首页
     */
    private fun toMain() {
        val mainIntent = Intent(this, MainActivity::class.java)
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(mainIntent)
    }

    /**
     * 登录失败
     */
    private fun showLoginFailed(error: LoginFail) {
        when (error) {
            LoginFail.NO_SUCH_USER -> MaterialDialog(this).show {
                title(R.string.title_no_such_user)
                message(null, "是否需要以当前信息进行注册")
                positiveButton(null, "确定") {
                    it.dismiss()
                    doRegister()
                }
            }
            LoginFail.PASSWORD_WRONG -> Toast.makeText(
                applicationContext,
                "密码错误",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    /**
     * 注册
     */
    private fun doRegister() {
        loginViewModel.registerUser(
            binding.username.text.toString(),
            binding.password.text.toString()
        ).observe(this) {
            if (-1L == it) {
                Toast.makeText(applicationContext, "注册失败", Toast.LENGTH_SHORT).show()
            } else {
                toMain()
            }
        }
    }
}

/**
 * 扩展函数，监听输入框内容变化
 */
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    })
}